<template>
	<view>



		<view class="content1">
			<view class="boxLogo">
				<image class="logoImg" src="/static/images/logo.png" mode="" />
			</view>
			<view class="logoText">玖盛谷台球俱乐部</view>
			<view class="l3">
				<radio class="agreeRadio" @tap="toggleAgree" value="r1" :checked="isAgree" color="#001C71"
					style="width: 30rpx; height: 30rpx" />
				<view class="tipsText">
					我已认真阅读、理解并同意
					<text @tap="goUserAgreement">《玖盛谷用户协议》《玖盛谷隐私权政策》</text>
				</view>
			</view>
		</view>
		<button class="btn" @tap="login" :open-type="openType" @getphonenumber="handlePhoneAuth">一键登录</button>
		<!-- <view class="backHome" @tap="goBackHome">返回首页</view> -->
		<!-- <button id="hiddenPhoneBtn" open-type="getPhoneNumber" bindgetphonenumber="handlePhoneAuth" style="position:absolute;opacity:0;width:200rpx;height:200rpx;top:50%;left:50%;transform:translate(-50%,-50%);"></button> -->
		<!-- <view v-if="showAuthMask" class="auth-mask" @tap="triggerAuth">
			<button class="hidden-phone-btn" id="hiddenPhoneBtn" open-type="getPhoneNumber"
				@getphonenumber="handlePhoneAuth"></button>
			<view class="guide-content">
				<text class="guide-text">请授权手机号以继续使用</text>
			</view>
		</view> -->
	</view>
</template>

<script setup>
	import {
		ref,
		reactive
	} from 'vue'
	import {
		loginApi
	} from '@/api/login'
	import { onLoad } from '@dcloudio/uni-app'

	// 状态定义
	const isAgree = ref(false)
	const phoneInfo = ref(null)
	const showAuthMask = ref(false)
	const userInfo = ref(null)
	const invitation = ref(null)
	const showAuthTip = ref(false)
	const openType = ref('')
	const lastPage = ref(null)
	const lastParams = ref(null)

	onLoad((options) => {
		console.log('登录页面参数',options)
		getWxCode().then((code)=>{
			uni.setStorageSync('wx_code', code)
			console.log('options',code)
		})
		if(options.lastPage){
			lastPage.value = options.lastPage
		}
		if(options.params){
			lastParams.value = JSON.parse(options.params)
		}
	})

	const goBackHome = () => {
		uni.switchTab({
			url: '/pages/index/index'
		})
	}

	// 登录
	const login = async () => {
		if (!isAgree.value) {
			uni.showToast({
				title: '请先同意协议',
				icon: 'none'
			})
			return
		}
		try {
			// 2. 获取用户信息
			const userProfile = await getUserProfile()
			console.log('用户信息:', userProfile)
			// 1. 获取微信登录code
			const code = await getWxCode()
			uni.setStorageSync('wx_code', code)
			//保持是否登录
			console.log('获取微信code:', code)
			// 3. 显示手机号授权引导
			// showAuthMask.value = true
		} catch (err) {
			console.error('登录流程异常:', err)
			uni.showToast({
				title: '登录失败，请重试',
				icon: 'none'
			})
		}
	}

	// 获取微信登录code
	const getWxCode = () => {
		return new Promise((resolve, reject) => {
			uni.login({
				provider: 'weixin',
				success: (res) => {
					if (res.code) {
						resolve(res.code)
					} else {
						reject(new Error('获取微信code失败'))
					}
				},
				fail: (err) => {
					console.error('微信登录失败:', err)
					reject(err)
				}
			})
		})
	}

	// 获取用户信息
	const getUserProfile = () => {
		return new Promise((resolve, reject) => {
			uni.getUserProfile({
				desc: '用于完善会员资料',
				success: (res) => {
					userInfo.value = res.userInfo
					console.log('获取用户信息', res);
					resolve(res.userInfo)
				},
				fail: (err) => {
					console.error('获取用户信息失败:', err)
					reject(err)
				}
			})
		})
	}

	// 手机号授权回调
	const handlePhoneAuth = async (e) => {
		// 关闭引导层
		showAuthMask.value = false

		// 验证授权结果
		if (e.detail.errMsg !== 'getPhoneNumber:ok') {
			throw new Error('用户拒绝手机号授权')
		}

		// 获取本地存储的code
		const code = uni.getStorageSync('wx_code')
		if (!code) {
			throw new Error('微信登录已过期，请重新登录')
		}

		// 调用登录接口
		const params = {
			code,
			encryptedData: e.detail.encryptedData,
			iv: e.detail.iv,
			Invitation: invitation.value,
			avatarUrl: userInfo.value.avatarUrl,
			nickName: userInfo.value.nickName,
			gender: userInfo.value.gender,
		}
		// TODO: 替换为实际的登录接口
		const res = await loginApi(params)
		if (res.code === 200) {
			// 登录成功，存储用户信息
			// uni.setStorageSync('token', res.data.data.token)
			uni.setStorageSync('userInfo', res.result)
			uni.setStorageSync('isLogin', true)
			// 跳转到首页
			if(lastPage.value){
				//关闭所有页面
				uni.reLaunch({
					url: '/'+lastPage.value+'?params='+JSON.stringify(lastParams.value)
				})
			}else{
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		} else {
			uni.showToast({
				title: res.message || '登录失败',
				icon: 'none'
			})
		}
	}

	// 去用户协议页
	const goUserAgreement = () => {
		uni.navigateTo({
			url: '/SubApp/pages/UserAgreement/UserAgreement'
		})
	}

	// 同意协议
	const toggleAgree = () => {
		if (!isAgree.value) {
			openType.value = 'getPhoneNumber'
		} else {
			openType.value = ''
		}
		isAgree.value = !isAgree.value
	}

	// 返回上一页
	const goPreurl = () => {
		uni.navigateBack()
	}

	// 触发授权
	const triggerAuth = () => {
		const query = uni.createSelectorQuery()
		query
			.select('#hiddenPhoneBtn')
			.boundingClientRect((rect) => {
				if (rect) {
					showAuthMask.value = false
					showAuthTip.value = true
				}
			})
			.exec()
	}
</script>

<style>
	.content1 {
		width: 100%;
		position: relative;
		overflow: hidden;
	}

	.content1 .boxLogo {
		width: 100%;
		margin-top: 320rpx;
		display: flex;
		justify-content: center;
	}

	.logoImg {
		width: 142rpx;
		height: 122rpx;
		margin: 0 auto;
	}

	.logoText {
		width: 100%;
		text-align: center;
		font-family: PingFang SC, PingFang SC;
		font-weight: bold;
		font-size: 44rpx;
		color: #000000;
		padding-top: 30rpx;
	}

	.content1 .l2 {
		position: absolute;
		top: 100%;
		width: 60%;
		height: 6%;
		left: 20%;
		opacity: 0;
	}

	.content1 .l3 {
		width: 100%;
		text-align: center;
		margin-top: 150rpx;
		display: flex;
		align-items: center;
		justify-content: flex-start;
		padding: 30rpx;
		box-sizing: border-box;
	}

	.agreeRadio {
		width: 20rpx;
		height: 20rpx;
		display: flex;
		flex: 1;
		align-items: top;
	}

	.content1 .l3 .tipsText {
		flex: 9;
		font-size: 26rpx;
		color: #000;
		text-align: left;
	}

	.content1 .l3 view text {
		color: #001c71;
	}

	.back {
		position: fixed;
		width: auto;
		left: 5%;
		box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.5);
		border-radius: 100000px;
	}

	.btn {
		width: 630rpx;
		height: 92rpx;
		line-height: 92rpx;
		text-align: center;
		background-color: #001c71;
		border-radius: 102rpx 102rpx 102rpx 102rpx;
		color: #ffffff;
		margin: 30rpx auto;
	}

	.auth-mask {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.8);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;
	}

	.hidden-phone-btn {
		position: absolute;
		top: 50%;
		left: 50%;
		width: 200rpx;
		height: 200rpx;
		transform: translate(-50%, -50%);
		opacity: 0;
		z-index: 1000;
		/* 确保按钮在遮罩层上方 */
	}

	.guide-content {
		position: relative;
		text-align: center;
	}

	.arrow {
		width: 48rpx;
		height: 48rpx;
		margin-bottom: 24rpx;
		animation: bounce 1s infinite;
	}

	.guide-text {
		color: white;
		font-size: 32rpx;
	}

	@keyframes bounce {

		0%,
		100% {
			transform: translateY(0);
		}

		50% {
			transform: translateY(-20rpx);
		}
	}
</style>